var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

var md5 = require('md5-node');
var DB=require('../../model/db.js');
var session = require("express-session");

router.use(session({   /*注意复制代码的时候要改 app*/
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));

//引入数据
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));

var Config=require('../../model/config.js').config;

//var HOST=''
//app.use(function(req, res,next){
//  HOST="http://"+req.headers.host;/*获取到了一个域名*/
//
//  next();
//
//})

/* GET users listing. */
router.get('/', function(req, res) {
  //res.send('用户登录');
  console.log(Config);

  //console.log(req.headers.host);  /*获取到了一个域名*/

  res.render('admin/login',{
    //
    host:Config.HOST
  });

});

router.post('/doLogin', function(req, res) {
  //res.send('执行登录操作');

  console.log(req.body);

  var username=req.body.username;

  var password=md5(req.body.password);



      DB.find('admin',{
        username,
        password
      },function(err,data){

          if(err){
            console.log('登录失败');
            return;

          }
          //console.log(data);
          if(data.length>0){

            console.log('登录成功');

            req.session.userinfo=data[0];

            res.redirect(Config.HOST+'admin/index');  /*跳转绝对路径*/

          }else{

              console.log('登录失败');
            //  res.redirect(Config.HOST+'admin/login');  /*跳转绝对路径*/   /*注意登录失败给个提示*/

            //var loginHost=Config.HOST+'admin/login';

            res.send("<script>alert('登录失败');location.href='http://localhost:3000/admin/login'</script> ")
          }
      })


});

module.exports = router;
